﻿/* Copyright DepencyCatalog.cs Killian Bourrié
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

namespace NTracker.Injection
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using Configs;

    public sealed class DependencyCatalog : IBaseCatalog
    {
        private static DependencyCatalog instance;
        private ConfigResources configuration;
        private IDictionary<string, string> patternsLibrary;
        private IDictionary<string, string> modulesDirectory;

        private DependencyCatalog()
        {
            this.configuration = new ConfigResources();
            this.Dependencies = new Dictionary<string, Type>();
            this.patternsLibrary = this.configuration.PatternsAssemblyFile;
            this.modulesDirectory = this.configuration.DirectoriesAssemblyFile;
        }

        public static DependencyCatalog Instance
        {
            get
            {
                // implementation of Singleton Pattern 
                if (instance == null)
                {
                    instance = new DependencyCatalog();
                }

                return instance;
            }
        }

        public IDictionary<string, Type> Dependencies { get; set; }

        public void RefreshDependencies()
        {
            IEnumerable<Assembly> assemblies = this.LoadAssemblies();
            this.PopulateCatalog(assemblies);
        }

        private List<Assembly> LoadAssemblies()
        {
            List<Assembly> assemblies = new List<Assembly>();
            List<string> files = new List<string>();
            foreach (var directory in this.modulesDirectory)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), directory.Value);
                
                foreach (var file in this.patternsLibrary)
                {
                    files.AddRange(Directory.GetFiles(path, file.Value).ToList());
                }
            }

            foreach (string dll in files)
            {
                assemblies.Add(Assembly.LoadFile(dll));
            }

            return assemblies;
        }

        private void PopulateCatalog(IEnumerable<Assembly> assemblies)
        {
            if (this.Dependencies != null)
            {
                this.Dependencies = new Dictionary<string, Type>(); 
            }

            // retrieve all classes who implements our custom attributes
            foreach (Assembly assembly in assemblies)
            {
                IEnumerable<Type> types = assembly.GetTypes()
                        .Where(t => t.GetCustomAttributes(true).Count() != 0);

                if (types != null)
                {
                    foreach (Type type in types)
                    {
                        IEnumerable<object> attributes = type.GetCustomAttributes(true)
                                .Where(a => a.GetType() == typeof(BroadcastAttribute));

                        if (attributes != null)
                        {
                            foreach (object attribute in attributes)
                            {
                                BroadcastAttribute broadcast = (BroadcastAttribute)attribute;
                                this.Dependencies.Add(broadcast.ContractName, type);
                            }
                        }
                    }
                }
            }
        }
    }
}
